import {ref} from 'vue'
import { DocumentGroupProperties } from '../common';
import { GroupProperties } from '../index'
import { BaseTaskProperties } from './Task'
import { detailService } from '../../../../../api/service'
import SvcSelect from '../../../components/svc-select'
import SvcParamsEditor from '../../../components/svc-params-editor'
import { ModdleElement } from '../../type'
import { BpmnStore } from '../../store'

interface PropertyElement {
  $type: string;
  name: string;
  value: unknown;
}

/**
 * 服务任务属性配置
 */
let flag = false
const inParamsOption = ref([])
// 获取详情内容
const getInParamsOption = async () => {
  const active = BpmnStore.getActiveElement().element?.di?.bpmnElement
  const svcId = active.extensionElements?.values?.find(item => item.name === 'resSvcIdExpression').expression

  const res = await detailService(svcId)
  if (res.status === 200) {
    inParamsOption.value = res.data.inParamsList
  }
}

export const BpmnServiceGroupProperties: GroupProperties = {
  name: '服务设置',
  icon: 'el-icon-user-solid',
  properties: {
    /**
     * 服务url属性
     */
    resSvcIdExpression: {
      component: SvcSelect,
      getValue: (businessObject: any): string => {
        if (!flag) {
          getInParamsOption()
          flag = true
        }
        return businessObject?.extensionElements?.values
          ?.filter((item: PropertyElement) => item.name === 'resSvcIdExpression')[0]
          ?.expression
      },
      setValue(businessObject: ModdleElement, key: string, value: string): void {
        const bpmnContext = BpmnStore;
        const moddle = bpmnContext.getModeler().get('moddle');
        const properties = moddle.create(`activiti:Field`, {
          name: key,
          expression: value
        });
        bpmnContext.updateExtensionElementsByAttr('activiti:Field', 'name', key, properties);
        flag = false
        // getInParamsOption() // 选择了服务url时调用获取inParams的接口更新数据
      }
    },
    /**
     * 入参设置
     */
    paramsExpression: {
      component: SvcParamsEditor,
      inParams: inParamsOption,
      getValue: (businessObject: any): string => {
        return businessObject?.extensionElements?.values
          ?.filter((item: PropertyElement) => item.name === 'paramsExpression')[0]
          ?.expression
      },
      setValue(businessObject: ModdleElement, key: string, value: []): void {
        const bpmnContext = BpmnStore;
        const moddle = bpmnContext.getModeler().get('moddle');
        const properties = moddle.create(`activiti:Field`, {
          name: key,
          expression: value
        });
        bpmnContext.updateExtensionElementsByAttr('activiti:Field', 'name', key, properties);
      },
    }
  },
};

export default {
  'bpmn:ServiceTask': [
    BaseTaskProperties,
    BpmnServiceGroupProperties,
    DocumentGroupProperties,
  ],
};
